package gui;

import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import model.Database;

/**
 * Window class it he JFrame which the visual output is within. It sets up the system and exits if user quits or if connection couldn't be created.
 */
public class Window extends JFrame{

	private static final int xSize = 600;
	private static final int ySize = 600;
	
	private JTabbedPane main;
	private Database db;
	
	/**
	 * Is the constructor which creates the database.
	 * @param db is the database which accesses the database model.
	 */
	public Window(Database db){
		this.db = db;
		Dimension d  = new Dimension(xSize, ySize);
		setSize(d);
		setPreferredSize(d);
		add(main=new JTabbedPane());
		main.addTab("Produce",new ProducePanel(db));
		main.addTab("Search & Block", new SearchPanel(db));
		setVisible(true);
		addWindowListener(new WindowAdapter(){
			/**
			 * windowClosing triggers the exit() method.
			 * @param arg0 is the WindowEvent telling the system the user is trying to destroy window.
			 */
			public void windowClosing(WindowEvent arg0) {
				exit();
			}
		});
	}
	/**
	 * exit() closes the connection and quits the system
	 */
	public void exit(){
		db.closeConnection();
		System.exit(0);
	}
	/**
	 * main is the main method which starts the application.
	 * If there are less than 2 params then a default username and password is given.
	 * Else param[0] is the username and param[2] is the password used to access the database.
	 * @param e is the params sent into the system.
	 */
	public static void main(String[] e){
			Database db = new Database();
			String userName = "db70";
			String password = "radish";
			if(e.length>1){
				userName = e[0];
				password = e[1];
			}
			if(!db.openConnection(userName, password)){
				System.out.println("User "+userName+" could not access the database with given password.");
				System.exit(0);
			}
			new Window(db);
	}
	
}
